package algorithm.measures;

import java.text.DecimalFormat;

import utility.file.TextFile;

public class BinaryConfusionMatrix {
	
	private int _falseNegatives;
	private int _falsePositives;
	private int _trueNegatives;
	private int _truePositives;
	public BinaryConfusionMatrix(){
		_truePositives = 0;
		_trueNegatives = 0;
		_falsePositives = 0;
		_falseNegatives = 0;
	}
	
	public double f1Measure() {
		double numerator = 2*precision()*recall();
		double denominator = precision()+recall();
		if(denominator==0) return 0;
		
		return numerator/denominator;
	}

	public double breakEven() {
		return ((precision()+recall())/2);
	}

	public double recall() {
		double denominator = _truePositives+_falseNegatives;
		if(denominator==0) return 0;
		
		return (double)((_truePositives)/denominator);
	}

	public double precision() {
		double denominator = _truePositives+_falsePositives;
		if(denominator==0) return 0;
		
		return (double)((_truePositives)/denominator);
	}

	public double accuracy(int trainingNumber) {
		return (1-errorRate(trainingNumber));
	}

	public double errorRate(int trainingNumber) {
		if(trainingNumber==0) return 0;
		
		double result = ((double)(_falsePositives+_falseNegatives)/trainingNumber);
		return result;
	}

	public void addTruePositives(int increment) {
		_truePositives+=increment;
	}

	public void addFalseNegatives(int increment) {
		_falseNegatives+=increment;
	}

	public void addFalsePositives(int increment) {
		_falsePositives+=increment;
	}

	public void addTrueNegatives(int increment) {
		_trueNegatives+=increment;
	}

	public void writeResultsForOn(int numberOfElements, String name, TextFile file) {
		DecimalFormat decimalFormat = new DecimalFormat("#.000");
		
		StringBuffer result = new StringBuffer();
		result.append(numberOfElements);
		result.append(";;");
		result.append(name);
		result.append(";");
		result.append(_truePositives);
		result.append(";");
		result.append(_falsePositives);
		result.append(";");
		result.append(_falseNegatives);
		result.append(";");
		result.append(_trueNegatives);
		result.append(";");
		result.append(";");
		result.append(decimalFormat.format(errorRate(numberOfElements)));
		result.append(";");
		result.append(decimalFormat.format(accuracy(numberOfElements)));
		result.append(";");
		result.append(decimalFormat.format(precision()));
		result.append(";");
		result.append(decimalFormat.format(recall()));
		result.append(";");
		result.append(decimalFormat.format(breakEven()));
		result.append(";");
		result.append(decimalFormat.format(f1Measure()));
		
		file.putLineInCache(result.toString());
	}

	

}
